package cn.wolfcode.luowowo.member.service;


import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.customexception.UserInfoException;
import cn.wolfcode.luowowo.common.domain.AjaxResult;
import cn.wolfcode.luowowo.common.key.RedisKey;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.MD5Util;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImple implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;


    @Override
    public boolean checkPhone(String phone) {

        return !(userInfoMapper.selectCountByPhone(phone) > 0);

    }

    @Override
    public void sendVerifyCode(String phone) {

        AssertUtil.hasLength(phone, "手机号不能为空");

        AssertUtil.matchPattern(phone, "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$", "手机号码格式错误");

        if (userInfoMapper.selectCountByPhone(phone) > 0) {
            throw new UserInfoException("手机号已被注册");
        }

        //生成验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);

        //先行缓存验证码同时判断是否是否已经发送过短信
        userInfoRedisService.sendVerifyCode(phone, code);

        //发送短信
        StringBuilder sb = new StringBuilder();

        sb.append("您的验证码是:").append(code).append(",请在3分钟内使用");

        System.err.println(sb.toString());

    }

    @Override
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //对参数合法性进行验证
        AssertUtil.hasLength(phone, "手机号不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "二次密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");

        AssertUtil.matchPattern(phone, "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$", "手机号码格式错误");

        if (userInfoMapper.selectCountByPhone(phone) > 0) {
            throw new UserInfoException("手机号已被注册");
        }

        AssertUtil.isEquals(password, rpassword, "两次密码输入不一致");

        String code = userInfoRedisService.getVerifyCodeByPhone(phone);

        AssertUtil.isEquals(verifyCode, code, "验证码不一致");

        //注册
        UserInfo userInfo = new UserInfo();

        userInfo.setPhone(phone);
        userInfo.setNickname(nickname);

        //加密
        userInfo.setPassword(MD5Util.EncoderByMd5(password));

        userInfo.setHeadImgUrl("/images/copyright.png");
        userInfo.setLevel(1);
        userInfo.setState(UserInfo.STATE_NORMAL);

        userInfoMapper.insert(userInfo);
    }

    @Override
    public String userLogin(String username, String password) {

        AssertUtil.hasLength(username, "手机号不能为空");

        AssertUtil.hasLength(password, "密码不能为空");

        UserInfo userInfo = userInfoMapper.selectByUsernameAndPassword(username, MD5Util.EncoderByMd5(password));

        AssertUtil.isNull(userInfo,"账号不存在或者密码错误");

        //将登录成功的信息缓存到Redis
        String token = UUID.randomUUID().toString().replaceAll("-","");

        userInfoRedisService.setLoginUserInfo(token, JSON.toJSONString(userInfo));

        return token;

    }

    @Override
    public List<UserInfo> list() {

        return userInfoMapper.selectAll();
    }

    @Override
    public void updateHeadImgUrl(Long uid, String pic) {
        userInfoMapper.updateHeadImgUrl(uid,pic);
    }

    @Override
    public void updateUserInfo(UserInfo userInfo) {
        UserInfo user = new UserInfo();
        user.setId(userInfo.getId());
        user.setNickname(userInfo.getNickname());
        user.setGender(userInfo.getGender());
        user.setCity(userInfo.getCity());
        user.setBirthday(userInfo.getBirthday());
        user.setInfo(userInfo.getInfo());
        //收货地址
        //user.set
        userInfoMapper.updateUserInfo(user);
    }

    @Override
    public AjaxResult updatepassword(String password,String rpassword1,String rpassword2,String smscode,String phone) {
        userInfoMapper.updatepassword(rpassword1,phone);
        return new AjaxResult();

    }

    @Override
    public void updateEmailById(String email, Long id) {
        userInfoMapper.updateEmailById(email,id);
    }

    @Override
    public void updateStateById(int state, Long id) {
        userInfoMapper.updateStateById(state,id);
    }

    @Override
    public void updatePhoneById(String phone, Long id) {
        userInfoMapper.updatePhoneById(phone,id);
    }

    @Override
    public UserInfo selectUserById(Long uid) {
        return userInfoMapper.selectByPrimaryKey(uid);
    }



    @Override
    public void sendrpwVerifyCode(String phone) {
        AssertUtil.hasLength(phone, "手机号不能为空");

        AssertUtil.matchPattern(phone, "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$", "手机号码格式错误");

        if (userInfoMapper.selectCountByPhone(phone) < 0) {
            throw new UserInfoException("手机号不存在");
        }

        //生成验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);

        //先行缓存验证码同时判断是否是否已经发送过短信
        userInfoRedisService.sendVerifyCode(phone, code);

        //发送短信
        StringBuilder sb = new StringBuilder();

        sb.append("您的验证码是:").append(code).append(",请在3分钟内使用");

        System.err.println(sb.toString());
    }

    @Override
    public void  updateScore(Long id, BigDecimal score) {
        if(id != null && score != null){
            userInfoMapper.updateScore(id,score);

        }
    }




    //更新userInfo
    public void update(UserInfo userInfo,String token) {
        userInfoMapper.updateByPrimaryKey(userInfo);
        // 根据userInfo的id查询数据
        UserInfo newUser = userInfoMapper.selectByPrimaryKey(userInfo.getId());
        //将数据保存到redis中
        //userInfoRedisService.addToken(RedisKey.TOKEN_COOKIE_NAME, token, newUser);
    }

    @Override
    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public String queryFansByUid(Long uid) {
        return userInfoMapper.selectFansByUid(uid);
    }

    @Override
    public String queryFollwersByUid(Long uid) {

        return userInfoMapper.selectFollwersByUid(uid);
    }

    @Override
    public Integer selectHoney(Long id) {
        return userInfoMapper.selectHoney(id);
    }
}
